package club.beidouqixing.base.stream;

import lombok.extern.slf4j.Slf4j;

import java.io.*;

@Slf4j
public class StreamUtil {

	public static final int BUFFER_SIZE = 8192;
	
	public static final byte[] inputStream2Bytes(InputStream is){
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		int c;
		try {
			while( (c=is.read())!=-1){
				os.write(c);
			}
		} catch (IOException e) {
			log.error("输出数据流错误！", e);
		}
		
		return os.toByteArray();		
	}
	
	public static final byte[] inputStream2BytesAndClose(InputStream is){
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		byte[] buff = new byte[1024];
		try {
			int c;
			while ((c = is.read(buff)) != -1) {
				os.write(buff, 0, c);
				os.flush();
			}
			os.flush();
		} catch (Exception e) {
			log.error("输出数据流错误。", e);
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					log.error("输入数据流关闭错误。", e);
				}
			}
			if (os != null) {
				try {
					os.close();
				} catch (Exception e2) {
					log.error("输出数据流关闭错误。", e2);
				}
			}
		}

		return os.toByteArray();
	}
	
	public static final byte[] toByteArray(InputStream is) throws IOException{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte buf[] = new byte[BUFFER_SIZE];
        int count;
		while ((count = is.read(buf, 0, BUFFER_SIZE)) != -1) {
			baos.write(buf, 0, count);
        }
		baos.flush();
		baos.close();
        
        return baos.toByteArray();
	}
	
	public static final void writeToFile(InputStream is, File file) throws IOException{
		file.createNewFile();
		OutputStream os = new FileOutputStream(file);
		try {
			byte buf[] = new byte[BUFFER_SIZE];
	        int count;
			while ((count = is.read(buf, 0, BUFFER_SIZE)) != -1) {
				os.write(buf, 0, count);
	        }
			os.flush();
		} finally {
			if (os != null){
				try {
					os.close();
				} catch (Exception e) {
				}
			}
		}
	}
	
	public static final void writeToFileAndClose(InputStream is, File file) throws IOException{
		file.createNewFile();
		OutputStream os = new FileOutputStream(file);
		try {
			byte buf[] = new byte[BUFFER_SIZE];
	        int count;
			while ((count = is.read(buf, 0, BUFFER_SIZE)) != -1) {
				os.write(buf, 0, count);
	        }
			os.flush();
		} finally {
			if (os != null){
				try {
					os.close();
				} catch (Exception e) {
				}
			}
			if (is != null){
				try {
					is.close();
				} catch (Exception e) {
				}
			}
		}
	}

}
